package test.abcode.image.service;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import test.abcode.image.pojo.TextRegion;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ImageTranslationService {

    private final TranslatorService translatorService;
    private final ImageEditor imageEditor;

    @Value("${tesseract.install-path}")
    private String installPath;

    @Value("${tesseract.data-path}")
    private String dataPath;

    @Value("${image.output-path}")
    private String outputImagePath;

    public ImageTranslationService(TranslatorService translatorService, ImageEditor imageEditor) {
        this.translatorService = translatorService;
        this.imageEditor = imageEditor;

        // 设置 Tesseract 数据路径
        // System.setProperty("TESSDATA_PREFIX", installPath);  // 从配置文件读取安装路径
    }

    public void processImage(String inputImagePath, String targetLanguage, String imageName) throws Exception {
        // Step 1: 读取图片并提取文字
        BufferedImage image = ImageIO.read(new File(inputImagePath));
        //BufferedImage newImage = ImagePreprocessing.preprocessImage(image);
        Tesseract tesseract = new Tesseract();

        // 设置 Tesseract 数据路径
        tesseract.setDatapath(dataPath);  // 从配置文件读取数据路径
        tesseract.setLanguage("chi_sim+eng");
        // 设置 OCR 引擎模式为 LSTM
        tesseract.setOcrEngineMode(1);

        // 设置页面分割模式，可以根据实际情况调整
        tesseract.setPageSegMode(3);
        // 提取图片中的文字
        String extractedText = tesseract.doOCR(image);
        //  List<TextRegion> extractedTextList = extractTextWithRegions(image);
        log.info("从图片提取到的文字: {}", extractedText);

        // Step 2: 翻译文字
//        String translatedText = translatorService.translateText(extractedText, targetLanguage);
//
//        // Step 3: 替换图片中的文字
//        BufferedImage newImage = imageEditor.replaceTextInImage(image, translatedText, 100, 100);  // 设置文字位置
//
//        // Step 4: 保存新图片
//        imageEditor.saveImage(newImage, outputImagePath);
    }

    public List<TextRegion> extractTextWithRegions(BufferedImage image) throws TesseractException {
        // 初始化 Tesseract
        ITesseract tesseract = new Tesseract();
        tesseract.setDatapath(dataPath);
        tesseract.setLanguage("chi_sim+eng");
        tesseract.setPageSegMode(3);

        // 获取文本区域信息
        List<Word> words = tesseract.getWords(image, ITessAPI.TessPageIteratorLevel.RIL_WORD);

        return words.stream()
                .map(word -> new TextRegion(word.getText(), word.getBoundingBox(), word.getConfidence(), ""))
                .collect(Collectors.toList());
    }
}
